const express = require("express");
const Note = require("@models/note");
const authenticateToken = require("@middleware/auth");
const router = express.Router();

// 所有笔记接口都需要JWT验证
router.use(authenticateToken);

// 1. 创建笔记
router.post("/createNote", async (req, res) => {
  try {
    const { title, content } = req.body;
    const userId = req.user._id;

    // 参数验证
    if (!title || !content) {
      return res.status(200).json({
        success: false,
        message: "标题和内容不能为空"
      });
    }

    // 创建笔记
    const note = new Note({
      title,
      content,
      userId
    });

    await note.save();

    res.status(201).json({
      success: true,
      message: "笔记创建成功",
    });
  } catch (error) {
    console.error("创建笔记错误:", error);
    res.status(500).json({
      success: false,
      message: "服务器错误"
    });
  }
});

// 2. 获取笔记列表
router.get("/noteList", async (req, res) => {
  try {
    const userId = req.user._id;
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;

    // 查询用户的笔记
    const notes = await Note.find({ userId })
      .sort({ createdAt: -1 }) // 按创建时间倒序
      .skip(skip)
      .limit(limit);

    // 获取总数
    const total = await Note.countDocuments({ userId });

    res.status(200).json({
      success: true,
      message: "获取笔记列表成功",
      data: {
        notes,
        pagination: {
          page,
          limit,
          total,
          pages: Math.ceil(total / limit)
        }
      }
    });
  } catch (error) {
    console.error("获取笔记列表错误:", error);
    res.status(500).json({
      success: false,
      message: "服务器错误"
    });
  }
});

// 3. 获取单条笔记
router.get("/noteDetail", async (req, res) => {
  try {
    const id = req.query.id;
    const userId = req.user._id;

    const note = await Note.findOne({ _id: id, userId });

    if (!note) {
      return res.status(200).json({
        success: false,
        message: "笔记不存在"
      });
    }

    res.status(200).json({
      success: true,
      message: "获取笔记详情成功",
      data: note
    });
  } catch (error) {
    console.error("获取笔记详情错误:", error);
    res.status(500).json({
      success: false,
      message: "服务器错误"
    });
  }
});

// 4. 更新笔记
router.put("/updateNote", async (req, res) => {
  try {
    const id = req.query.id;
    const { title, content } = req.body;
    const userId = req.user._id;

    // 参数验证
    if (!title || !content) {
      return res.status(200).json({
        success: false,
        message: "标题和内容不能为空"
      });
    }

    // 查找并更新笔记
    const note = await Note.findOneAndUpdate(
      { _id: id, userId },
      { 
        title, 
        content,
        updatedAt: Date.now()
      },
      { new: true } // 返回更新后的文档
    );

    if (!note) {
      return res.status(200).json({
        success: false,
        message: "笔记不存在"
      });
    }

    res.status(200).json({
      success: true,
      message: "笔记更新成功",
    });
  } catch (error) {
    console.error("更新笔记错误:", error);
    res.status(500).json({
      success: false,
      message: "服务器错误"
    });
  }
});

// 5. 删除笔记
router.delete("/deleteNote", async (req, res) => {
  try {
    const id = req.query.id;
    const userId = req.user._id;

    const note = await Note.findOneAndDelete({ _id: id, userId });

    if (!note) {
      return res.status(200).json({
        success: false,
        message: "笔记不存在"
      });
    }

    res.status(200).json({
      success: true,
      message: "笔记删除成功"
    });
  } catch (error) {
    console.error("删除笔记错误:", error);
    res.status(500).json({
      success: false,
      message: "服务器错误"
    });
  }
});

// 6. 搜索笔记（按标题）
router.get("/noteSearch", async (req, res) => {
  try {
    const { q } = req.query; // 搜索关键词
    const userId = req.user._id;
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;

    if (!q) {
      return res.status(200).json({
        success: false,
        message: "搜索关键词不能为空"
      });
    }

    // 使用正则表达式进行模糊搜索
    const searchRegex = new RegExp(q, 'i'); // i表示不区分大小写

    const notes = await Note.find({
      userId,
      title: searchRegex
    })
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit);

    const total = await Note.countDocuments({
      userId,
      title: searchRegex
    });

    res.status(200).json({
      success: true,
      data: {
        notes,
        pagination: {
          page,
          limit,
          total,
          pages: Math.ceil(total / limit)
        }
      }
    });
  } catch (error) {
    console.error("搜索笔记错误:", error);
    res.status(500).json({
      success: false,
      message: "服务器错误"
    });
  }
});

module.exports = router;

